<template>
    <div class="manual-dispatch">

    <!-- 订单信息 -->
    <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>订单信息</span>
        </div>
        <el-form :model="orderForm" label-width="100px" >  
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="修改申请编号">
                <el-input v-model="orderForm.applicationCode"  :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订单编号">
                <el-input v-model="orderForm.orderCode"  :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="订单状态">
                <el-input v-model="orderStatusText" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称">
                  <el-input v-model="orderForm.customerName" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售员姓名">
                <el-select v-model="orderForm.salespersonCode" placeholder="请选择销售员" >
                  <el-option v-for="sale in saleList" 
                  :key="sale.code"
                  :label="sale.realName"
                  :value="sale.code">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          
          </el-row>
        </el-form>
      </el-card>

       <!-- 产品明细卡片 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>产品明细</span>
      </div>

      <div style=" margin-bottom: 10px ">
        <el-button type="primary" size="small" @click="showProductDialog">+ 添加产品</el-button>
        <el-button 
          type="danger" 
          size="small" 
          @click="handleBatchDelete" 
          :disabled="!selectedDetails.length">
          批量删除
        </el-button>
      </div>
      <el-table 
        :data="productList" 
        border 
        style="width: 100%"
        @selection-change="handleDetailSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column prop="index" label="序号" width="80" align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="产品名称"></el-table-column>
        <el-table-column prop="productCode" label="产品编码"></el-table-column>
        <el-table-column prop="inventory" label="当前可用库存数量"></el-table-column>
        <el-table-column label="选择数量" width="220">
          <template slot-scope="scope">
            <el-input-number 
              v-model.number="scope.row.placeOrderNum" 
              :min="1" 
              :max="scope.row.inventory"
              :controls-position="'right'"
              @change="calculateTotal"
              :disabled="false">
            </el-input-number>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="unit" label="单位"></el-table-column> -->
        <el-table-column prop="univalent" label="单价"></el-table-column>
        <!-- <el-table-column prop="price" label="单品总价"></el-table-column> -->
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button 
              type="text" 
              size="small" 
              @click="handleDelete(scope.$index)" 
              style="color: #ff4949">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="total-amount-container">
        <div class="total-amount">
          <span class="total-label">产品总价值：</span>
          <span class="total-value">{{ totalAmount.toFixed(2) }}</span>
          <span class="currency">元</span>
        </div>
      </div>

    </el-card>



      <!-- 价格模块 -->
    <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>订单信息</span>
        </div>
        <el-form :model="orderForm" label-width="100px" >  
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="订单种类">
                <el-select v-model="orderForm.orderType" >
                  <el-option
                    v-for="item in orderTypes"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
                <el-form-item label="特价折扣">
                    <el-input-number 
                        v-model="orderForm.specialDiscount" 
                        :disabled="orderForm.orderType === 0" 
                        :min="0.6" 
                        :max="0.99" 
                        :step="0.1">
                    </el-input-number>
                </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

           <!-- 其他信息 -->
    <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>其他信息</span>
        </div>
        <el-form :model="orderForm" label-width="100px" >  
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="创建时间">
                <el-input v-model="orderForm.createTime"  :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建人">
                <el-input v-model="orderForm.createPerson"  :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="申请日期">
                <el-input v-model="orderForm.applicationDate"  :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="申请理由">
                <el-input v-model="orderForm.applicationReason"  :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="修改申请理由">
                <el-input v-model="orderForm.updateReason" ></el-input>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
      </el-card>

    
      <!-- 底部悬浮按钮 -->
    <div class="fixed-bottom">
        <div class="button-container">
            <el-button size="small" @click="returnOrderList">取消</el-button>
            <el-button size="small" type="primary" @click="submitProductApplication">申请修改</el-button>
        </div>
    </div>

   

    <!-- 产品选择弹窗 -->
    <el-dialog
      title="选择产品"
      :visible.sync="dialogVisible"
      width="70%">
      <el-table
        :data="productOptions"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column prop="productCode" label="产品编码"></el-table-column>
        <el-table-column prop="productName" label="产品名称"></el-table-column>
        <el-table-column prop="productStock" label="可用库存"></el-table-column>
        <el-table-column prop="productMaterial" label="产品物料"></el-table-column>
        <el-table-column prop="productDescription" label="产品描述"></el-table-column>
        <!-- <el-table-column prop="unit" label="单位"></el-table-column> -->
        <el-table-column prop="productPrice" label="单价"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSelection">确 定</el-button>
      </span>
    </el-dialog>
    </div>
  </template>
  
  <script>
  export default {
    // 订单编辑对话框是否可见
    name: 'ManualDispatch',
    // 订单表单数据对象
    data() {
      return {
        orderCode: '',
        orderForm: {}, //订单信息
        productList: [],
        productOptions: [],
        dialogVisible: false,
        selectedProducts: [],
        totalAmount: 0,
        selectedDetails: [],
        customerOptions: [],
        salesPersonOptions: [],
        orderTypes: [{ value: 0, label: '正常订单' }, { value: 1 , label: '特价订单' }],
        saleList: [],//销售员下拉框数据列表
      }
    },
    methods: {
      //生成修改申请编号
      createSnowId() {
      this.$axios.get("/api/order-server/order/createSnowId")
        .then(resp => {
          console.log(resp.data)
          if (resp.data.code == 200) {
            this.orderForm.applicationCode = resp.data.data
            console.log("=====================");
            console.log(this.orderForm.applicationCode);
          }
        })
      },
      //查询订单信息
      queryOrder(){
        this.$axios.get("/api/order-server/order/queryOrderById/"+this.orderCode)
            .then(resp =>{
              console.log(resp.data)
              if(resp.data.code==200){
              this.orderForm =resp.data.data
              // this.createSnowId()
              console.log("orderForm信息");
              console.log(this.orderForm);
            }
            })
      },
      //查询订单详情信息
      queryOrderDetials() {
        this.$axios.get("/api/order-server/order/queryOrderDetailById/" + this.orderCode)
          .then(resp => {
            console.log('数据库返回的产品列表:', resp.data.data);
            if (resp.data.code == 200) {
              this.productList = resp.data.data;
              // 在获取到产品列表数据后立即计算总价值
              this.calculateTotal();
            }
          });
      },

      // 查询客户列表
      queryCustomers() {
        this.$axios.post("/api/order-server/order/queryAllCustomer")
          .then(resp => {
            if (resp.data.code == 200) {
              this.customerOptions = resp.data.data;
            }
          })
          .catch(error => {
            console.error('获取客户列表失败:', error);
            this.$message.error('获取客户列表失败');
          });
      },
      //查询销售列表
      queryAllSale() {
      const roleId = 4;
      this.$axios.get("/api/order-server/uums/queryAllSale/" + roleId)
        .then(resp => {
          console.log(resp.data)
          if (resp.data.code == 200) {
            this.saleList = resp.data.data
          }
        })
    },
      returnOrderList(){
        //返回waybill页面
        this.$router.push({ path: '/order/orderList'})
      },
      // 展示产品选择弹窗   
      showProductDialog() {
        this.dialogVisible = true;
        this.$axios.get("/api/order-server/order/queryAllProduct")
          .then(resp => {
            console.log('数据库返回的产品列表:', resp.data.data);
            if (resp.data.code == 200) {
              this.productOptions = resp.data.data;
              // 在获取到产品列表数据后立即计算总价值
              this.calculateTotal();
            }
          });
      },

      // 处理表格选择变化
      handleSelectionChange(selection) {
        this.selectedProducts = selection;
      },

      // 确认选择产品
      confirmSelection() {
        let updateMessage = [];
        
        this.selectedProducts.forEach(product => {
          // 查找是否已存在相同产品编码的商品
          const existingProduct = this.productList.find(item => 
            item.productCode === product.productCode
          );
          
          if (existingProduct) {
            // 如果存在相同产品，检查是否超过库存限制
            if (existingProduct.placeOrderNum < existingProduct.inventory) {
              existingProduct.placeOrderNum += 1;
              updateMessage.push(`${existingProduct.productName}数量+1`);
            } else {
              updateMessage.push(`${existingProduct.productName}已达到最大库存限制`);
            }
          } else {
            // 添加新产品，使用正确的字段名称
            const newProduct = {
              productName: product.productName,
              productCode: product.productCode,
              inventory: product.productStock,  // 使用 productStock 作为库存
              placeOrderNum: 1,
              univalent: product.productPrice      // 使用 productPrice 作为价格
            };
            this.productList.push(newProduct);
            updateMessage.push(`已添加${newProduct.productName}`);
          }
        });

        // 只显示一次合并后的提示信息
        if (updateMessage.length > 0) {
          this.$message({
            type: 'success',
            message: updateMessage.join('；'),
            duration: 3000
          });
        }

        // 重新计算总金额
        this.calculateTotal();
        // 关闭对话框
        this.dialogVisible = false;
        // 清空选择
        this.selectedProducts = [];
      },

      // 删除产品
      handleDelete(index) {
        this.$confirm('确认删除该产品?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.productList.splice(index, 1);
          this.calculateTotal();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      // 计算总金额
      calculateTotal() {
        this.totalAmount = this.productList.reduce((sum, item) => {
          return sum + (item.placeOrderNum * item.univalent);
        }, 0);
      },

      // 处理产品明细表格的选择变化
      handleDetailSelectionChange(selection) {
        this.selectedDetails = selection;
      },

      // 批量删除
      handleBatchDelete() {
        if (this.selectedDetails.length === 0) {
          this.$message({
            type: 'warning',
            message: '请选择要删除的产品'
          });
          return;
        }

        this.$confirm(`确认删除选中的 ${this.selectedDetails.length} 个产品?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 获取要删除的产品的编码列表
          const deleteProductCodes = this.selectedDetails.map(item => item.productCode);
          
          // 过滤掉要删除的产品
          this.productList = this.productList.filter(item => 
            !deleteProductCodes.includes(item.productCode)
          );

          // 重新计算总金额
          this.calculateTotal();
          
          this.$message({
            type: 'success',
            message: '批量删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      // 提交方法
      submitProductApplication() {
        // 提交到后端
        this.$axios.post('/api/order-server/order/addApplication', {
          productList: this.productList,  // 直接传递整个productList数组
          orderCode: this.orderCode,
          status: this.orderForm.status,
          orderType: this.orderForm.orderType,
          customerName: this.orderForm.customerName,
          salesCode: this.orderForm.salespersonCode,
          depositAmount: this.orderForm.depositAmount,
          specialDiscount: this.orderForm.specialDiscount,
          createTime: this.orderForm.createTime,
          createPerson: this.orderForm.createPerson,
          applicationDate: this.orderForm.applicationDate,
          applicationReason: this.orderForm.applicationReason,
          updateReason: this.orderForm.updateReason,
          applicationCode:this.orderForm.applicationCode
        }).then(resp => {
          console.log("==========");
          console.log(this.productList);
          if (resp.data.code === 200) {
            this.$message.success('提交成功');
          } else {
            this.$message.error(resp.data.message || '提交失败');
          }
        }).catch(error => {
          console.error('提交失败:', error);
          this.$message.error('提交失败');
        });
      }

      

    },
    
    computed: {
      orderStatusText() {
        // 根据状态码返回对应的文本
        const statusMap = {
          1: '未结算',
          2: '修改审批中',
          3: '已完成',
          4: '审批不通过'
        };
        return statusMap[this.orderForm.status] || '未知状态';
      },
    
    },
    mounted() {
      
      this.createSnowId();
    },
    created(){
      this.orderCode = this.$route.query.orderCode;
      this.queryOrder();
      this.queryOrderDetials();
      this.queryAllSale();
    }
    
  }
  </script>
  
  <style scoped>
  .manual-dispatch {
    padding: 20px;
    padding-bottom: 60px; /* 为底部按钮出空间 */
  }
  .section {
    margin-bottom: 20px;
  }
  .fixed-bottom {
    width: 79%;
    margin-left: 240px; /*调整悬浮div左边距 */
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    padding: 10px 20px;
    text-align: right;
    box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
    z-index: 1000;
  }
  .button-container {
    display: flex;
    justify-content: flex-end; /* 使按钮靠右对齐 */
    padding-right: 20px; /* 右侧留出一些空间 */
    margin-left: 50px ;
    }
    .button-container .el-button {
    margin-left: 10px;
    }
    .box-card {
    margin-bottom: 20px;
  }

  .total-amount-container {
    margin-top: 20px;
    padding: 15px;
    text-align: right;
    background-color: #f8f9fa;
    border-radius: 4px;
  }

  .total-amount {
    display: inline-block;
  }

  .total-label {
    font-size: 14px;
    color: #606266;
  }

  .total-value {
    font-size: 20px;
    font-weight: bold;
    color: #409EFF;
    margin: 0 5px;
  }

  .currency {
    font-size: 14px;
    color: #606266;
  }

  </style>